<?php
namespace Api\Model;

class CategoryModel
{
    /**
     * 根目录paren_id
     * @var integer
     */
    private $parent_id = 0;
    /**
     * 获取所有分类
     * @return [type] [description]
     */
    private function getAll()
    {
        $categorys = M('category')
            ->field('id,name,image,thumb,description,parent_id')
            ->order('sort desc')
            ->select();
        return $categorys;
    }

    /**
     * 获取一级分类
     * @return [type] [description]
     */
    public function getParents()
    {
        $categorys = M('category')
            ->where([
                'parent_id' => $this->parent_id,
            ])
            ->field('id,name,image,thumb,description')
            ->order('sort desc')
            ->select();
        return $categorys;
    }

    /**
     * 获取子分类
     * @return [type] [description]
     */
    public function getChilds($parent_id)
    {
        $categorys = M('category')
            ->where([
                'parent_id' => $parent_id,
            ])
            ->field('id,name,image,thumb,description')
            ->order('sort desc')
            ->select();
        return $categorys;
    }

    /**
     * 生成树分类
     * @param  string $categorys [description]
     * @return [type]            [description]
     */
    public function getTree($parent_id, $categorys)
    {
        if (!count($categorys)) {
            return false;
        }

        $res = [];
        foreach ($categorys as $key => $category) {
            if ($category['parent_id'] == $parent_id) {
                unset($categorys[$key]);
                $category['child'] = $this->getTree($category['id'], $categorys);
                $res[]             = $category;
            }
        }

        return $res;
    }

    /**
     * 获取子节点
     * @param  integer $parent    [description]
     * @param  string  $categorys [description]
     * @return [type]             [description]
     */
    public function getChild($category_id)
    {
        $categorys = M('category')
            ->where([
                'parent_id' => $category_id,
            ])
            ->field('id,name,image,thumb,description,parent_id')
            ->order('sort desc')
            ->select();
        return $categorys;
    }

    /**
     *获取所有商品分类
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getAllTree()
    {
        $categorys = $this->getAll();
        $parent_id = $this->parent_id;

        $res = $this->getTree($parent_id, $categorys);

        return $res;
    }
}
